from cryptography.fernet import Fernet
from loguru import logger as logging


# 生成一个加密密钥
# key = Fernet.generate_key()
key = 'D5noDl8YkPGiKymbpdjViJ421gg89zVCfOgLGfYH1fU='
cipher_suite = Fernet(key)

def encrypt(data, mode='w') -> bytes:
    # 加密函数
    if not isinstance(data, bytes):
        data = data.encode('utf-8')
    # logging.info(f'encrypt, data: {data}, type: {type(data)}')
    #encrypted_data = bytes(byte ^ key for byte in data)
    encrypted_data = cipher_suite.encrypt(data)
    # logging.info(f'encrypt mode: {mode}, encrypted: {encrypted_data}, type: {type(encrypted_data)}')
    return encrypted_data

def decrypt(data, mode='r') -> bytes:
    # 解密函数
    if not isinstance(data, bytes):
        data = data.encode('utf-8')
    # logging.info(f'decrypt, data: {data}, type: {type(data)}')
    #decrypted_data = bytes(byte ^ key for byte in data)
    decrypted_data = cipher_suite.decrypt(data)
    # if 'b' not in mode:
    #     decrypted_data = decrypted_data.decode('utf-8')
    # logging.info(f'decrypt mode: {mode}, decrypted: {decrypted_data}, type: {type(decrypted_data)}')
    return decrypted_data
